package net.chenlin.dp.ids.server.controller;

import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.GlobalErrorEnum;
import net.chenlin.dp.ids.common.constant.IdsConst;
import net.chenlin.dp.ids.common.entity.SessionData;
import net.chenlin.dp.ids.common.entity.TicketValidateResultDTO;
import net.chenlin.dp.ids.common.util.CommonUtil;
import net.chenlin.dp.ids.server.manager.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * ids 客户端接口
 * @author zcl<yczclcn@163.com>
 */
@RestController
@RequestMapping("/client")
public class IdsClientController {

    private static final Logger logger = LoggerFactory.getLogger(IdsClientController.class);

    @Autowired
    private SessionManager sessionManager;

    /**
     * sessionId校验
     * @param appCode 接入passport应用标识
     * @param sessionId session中authId
     * @param loginType 登录终端类型
     * @return 登录状态，respData返回SessionData包含用户信息
     */
    @RequestMapping(value = IdsConst.AUTH_STATUS_URL, method = RequestMethod.POST)
    public BaseResult authStatus(@RequestParam String appCode, @RequestParam String sessionId,
                                 @RequestParam Integer loginType) {
        // 参数校验
        BaseResult checkResult = checkClient(appCode, sessionId, loginType);
        if (checkResult.bizError()) {
            return checkResult;
        }
        try {
            // 缓存获取用户信息
            SessionData sessionData = sessionManager.get(sessionId, loginType);
            // 用户信息为空，则初始化用户信息为未登录状态
            if (sessionData != null && sessionData.getLoginType().equals(loginType)) {
                // 返回用户信息
                return GlobalErrorEnum.SUCCESS.getResult().setRespData(sessionData);
            }
            // 返回业务异常，用户信息为空
            return GlobalErrorEnum.BizError.getResult();
        } catch (Exception e) {
            logger.error("客户端:{},manager:{} 校验异常：{}", appCode, sessionId, e);
            // 返回系统异常
            return GlobalErrorEnum.ERROR.getResult();
        }
    }

    /**
     * 刷新session过期时间
     * @param appCode 接入passport应用标识
     * @param sessionId session中authId
     * @param loginType 登录终端类型
     * @return
     */
    @RequestMapping(value = IdsConst.AUTH_REFRESH_URL, method = RequestMethod.POST)
    public BaseResult refreshStatus(@RequestParam String appCode, @RequestParam String sessionId,
                                    @RequestParam Integer loginType) {
        // 参数校验
        BaseResult checkResult = checkClient(appCode, sessionId, loginType);
        if (checkResult.bizError()) {
            return checkResult;
        }
        try {
            sessionManager.update(sessionId, loginType);
            return GlobalErrorEnum.SUCCESS.getResult();
        } catch (Exception e) {
            logger.error("客户端:{},manager:{} 刷新异常：{}", appCode, sessionId, e);
        }
        return GlobalErrorEnum.ERROR.getResult();
    }

    /**
     * 删除客户端session
     * @param appCode 接入passport应用标识
     * @param sessionId session中authId
     * @param loginType 登录终端类型
     * @return
     */
    @RequestMapping(value = IdsConst.AUTH_REMOVE_URL, method = RequestMethod.POST)
    public BaseResult removeStatus(@RequestParam String appCode, @RequestParam String sessionId,
                                   @RequestParam Integer loginType) {
        // 参数校验
        BaseResult checkResult = checkClient(appCode, sessionId, loginType);
        if (checkResult.bizError()) {
            return checkResult;
        }
        try {
            sessionManager.remove(sessionId, loginType);
            return GlobalErrorEnum.SUCCESS.getResult();
        } catch (Exception e) {
            logger.error("客户端:{},manager:{} 删除异常：{}", appCode, sessionId, e);
        }
        return GlobalErrorEnum.ERROR.getResult();
    }

    /**
     * 校验客户端ticket
     * @param appCode
     * @param ticket
     * @param loginType
     * @return
     */
    @RequestMapping(value = IdsConst.TICKET_VALID_URL, method = RequestMethod.POST)
    public BaseResult validateTicket(@RequestParam String appCode, @RequestParam String ticket,
                                     @RequestParam Integer loginType) {
        // 参数校验
        BaseResult checkResult = checkClient(appCode, ticket, loginType);
        if (checkResult.bizError()) {
            return checkResult;
        }
        TicketValidateResultDTO validateTicket = sessionManager.validateTicket(ticket, loginType);
        if (validateTicket != null) {
            return GlobalErrorEnum.SUCCESS.getResult().setRespData(validateTicket);
        }
        return GlobalErrorEnum.ERROR.getResult();
    }


    /**
     * 参数校验
     * @param appCode
     * @param sessionId
     * @return
     */
    private BaseResult checkClient(String appCode, String sessionId, Integer loginType) {
        // 接入系统编码，sessionId为空直接返回异常，防止非法调用，可增加appCode合法性校验
        if (CommonUtil.strIsEmpty(appCode) || CommonUtil.strIsEmpty(sessionId) || loginType == null) {
            return GlobalErrorEnum.BizError.getResult().setRespMsg("未注册的客户端调用授权");
        }
        return GlobalErrorEnum.SUCCESS.getResult();
    }

}
